﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Web;
using System.Web.Mvc;
using Client.Web.Models;
using WorkOrders.Domain.BLL;
using WorkOrders.Domain.Dtos;

namespace Client.Web.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string engineer)
        {
            return RedirectToAction("NextOrder", new {engineer});
        }

        public ActionResult NextOrder(string engineer)
        {
            var queue = GetQueue(engineer);
            if (queue != null)
            {
                try
                {
                    var message = queue.Receive(new TimeSpan(0, 0, 5));
                    if (message != null)
                    {
                        var workOrder = message.Body as WorkOrderDto;
                        if (workOrder != null)
                            return View(workOrder);
                    }
                }
                catch (MessageQueueException)
                {
                    return RedirectToAction("Empty", new { engineer });
                }
            }
            return RedirectToAction("Empty", new { engineer });
        }

        public ActionResult NextOrder(WorkOrderDto workOrder)
        {
            new CustomerManager().UpdateStatus(workOrder.CustomerId, workOrder.Status);
            return RedirectToAction("NextOrder", new {engineer = workOrder.Engineer});
        }

        public ActionResult Empty(string engineer)
        {
            return View(new EmptyQueueModel {Engineer = engineer});
        }

        private static MessageQueue GetQueue(string engineer)
        {
            var queueName = string.Format(@".\Private$\{0}", engineer);
            return MessageQueue.Exists(queueName) ? new MessageQueue(queueName) : null;
        }
    }
}
